package com.chen.service.impl;


import com.chen.entity.dto.SMSDto;
import com.chen.service.SMSService;
import com.chen.util.HttpUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SMSServiceImpl  implements SMSService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 获取短信验证码接口
     * @param smsDto
     */
    @Override
    public void getCode(SMSDto smsDto) {
        String phone = smsDto.getPhone();
       // 先去redis中查,看看有没有当前手机号所对应的验证码
        String s = redisTemplate.opsForValue().get("phone:code" + phone);
        //如果有就不给用户发验证码了, 说明当前验证码还没过期
        if(!StringUtils.isEmpty(s)){
            return;
        }
        // 如果没有就发送随机生成一个验证码
        String code = RandomStringUtils.randomNumeric(4);//随机生成四位数字验证码
        //保存到redis一份, 下一个注册接口要用到
        redisTemplate.opsForValue().set("phone:code"+phone,code,5, TimeUnit.MINUTES);
        // 调用第三方接口给用户发送短信
        System.out.println(code);  //可以发送到控制台
//        sendCodeApi(phone,code);
    }
    /**
     * 第三方发送短信的接口
     * @param phone
     * @param code
     */
    private void sendCodeApi(String phone, String code) {
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "acea7c6bec8a48318ef4656636945d2b";   //你自己的AppCode
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone); //第二个参数填写接受参数的手机号
        querys.put("param", "**code**:"+code+",**minute**:5"); // 把生成的验证码发给用户

        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
